﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="TestRunModule.cs" company="">
//   
// </copyright>
// <summary>
//   Defines the TestRunModule type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace UITest.Helpers.TFS
{
    using System.Collections.Generic;
    using System.Linq;

    using Microsoft.TeamFoundation.TestManagement.Client;

    /// <summary>
    /// </summary>
    public class TestRunModule : TFSModule
    {
        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="TestRunModule"/> class. 
        /// </summary>
        /// <param name="tfs">
        /// </param>
        public TestRunModule(TFSLibrary tfs)
            : base(tfs)
        {
        }

        #endregion

        #region Public Methods and Operators

        /// <summary>
        /// </summary>
        /// <param name="id">
        /// </param>
        /// <returns>
        /// The <see cref="ITestRun"/>.
        /// </returns>
        public ITestRun Find(int id)
        {
            return this.TFS.TestManagement.TestRuns.Find(id);
        }

        /// <summary>
        /// </summary>
        /// <param name="query">
        /// </param>
        /// <returns>
        /// The <see cref="IEnumerable"/>.
        /// </returns>
        public IEnumerable<ITestRun> Query(string query)
        {
            return this.TFS.TestManagement.TestRuns.Query(query);
        }

        /// <summary>
        /// </summary>
        /// <param name="run">
        /// </param>
        /// <returns>
        /// The <see cref="ITestCaseResultCollection"/>.
        /// </returns>
        public ITestCaseResultCollection QueryResults(ITestRun run)
        {
            return run.QueryResults();
        }

        /// <summary>
        /// Reruns failed test cases
        /// </summary>
        /// <param name="run">
        /// Test run to process
        /// </param>
        /// <returns>
        /// Iterable list of test results which were reset
        /// </returns>
        public IEnumerable<ITestCaseResult> ReRunFailed(ITestRun run)
        {
            run.Refresh();
            var list = new List<ITestCaseResult>();
            foreach (var result in run.QueryResults().Where(result => result.Outcome == TestOutcome.Failed))
            {
                result.Reset();
                list.Add(result);
            }

            return list;
        }

        #endregion
    }
}